package cate.game.role.res.guild.boss;

import cate.common.table.d.GDFunc;
import cate.common.table.d.GDGuild;
import cate.common.table.d.GDMail;
import cate.common.table.guild.guildboss.GuildBossRankRewardRow;
import cate.game.mail.po.MailBuilder;
import cate.game.rank.po.Rank;
import cate.game.res.MixRes;
import cate.game.role.Role;
import cate.game.role.mail.Mail;
import cate.common.table.guild.guildboss.GuildBossCombatRow;
import cate.game.role.res.guild.GuildFuncBase;
import cate.game.role.res.guild.po.GuildPO;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Slf4j
@NoteClass(value = "公会boss排行榜")
public class GuildBossRankPO extends GuildFuncBase {
    @NoteField(value = "已发放过第几关的排行榜奖励")
    public int combatNumRewardDone;

    @NoteField(value = "排行榜列表")
    public List<GuildBossRankItemPO> list;

    @Override
    public void initialize(GuildPO guild) {
        super.initialize(guild);
        if (list == null) {
            list = new ArrayList<>();
        }
    }

    /**
     * 根据唯一ID获取对应的排名
     *
     * @return -1表示没有进入排名
     */
    public int getIndex(String uid) {
        for (int i = 0; i < list.size(); i++) {
            Rank item = list.get(i);
            if (StringUtils.equals(item.owner.uid, uid)) {
                return i;
            }
        }
        return GDGuild.boss.RANK_NONE_INDEX;
    }

    /**
     * 根据主角唯一ID查找上榜记录
     */
    public GuildBossRankItemPO findByMaster(String masterIdHex) {
        for (GuildBossRankItemPO item : list) {
            if (StringUtils.equals(masterIdHex, item.owner.uid)) {
                return item;
            }
        }
        return null;
    }

    private void sort() {
        // damage 从大到小
        list.sort(Comparator.comparing(GuildBossRankItemPO::getDamage).reversed());
    }

    private int getMaxSize() {
        return 50;
    }

    /**
     * 记录
     *
     * @return 排行榜名次，如果返回-1表示没有入榜
     */
    public synchronized int record(Role role, long damage) {
        if (list.size() >= getMaxSize()) {
            GuildBossRankItemPO last = list.get(list.size() - 1);
            if (last.value > damage) {
                // 没有进排行榜
                return GDGuild.boss.RANK_NONE_INDEX;
            }
        }
        // 是否已经上榜
        GuildBossRankItemPO item = findByMaster(role.getUid());
        if (item != null) {
            // 已经在榜上了
            item.read(role, damage);
        } else {
            // 之前没有上榜
            item = new GuildBossRankItemPO(role, damage);
            if (list.size() >= getMaxSize()) {
                // 如果排行榜已经满了，那就把最后一名给去掉
                list.remove(list.size() - 1);
            }
            list.add(item);
        }
        sort();
        return getIndex(role.getUid());
    }

    /**
     * 被击杀之后，发放排行榜奖励
     */
    public synchronized void handleReward() {
        GuildPO guild = getFuncDependent().getGuild();
        if (combatNumRewardDone >= guild.boss.combatNumPass && !guild.boss.isLastCombat()) {
            return;
        }
        final GuildBossCombatRow combatTpl = guild.game.table.guildBoss.combat.get(guild.boss.combatNumPass);
        if (combatTpl != null) {
            List<GuildBossRankItemPO> temp = new ArrayList<>(list);
            list.clear();
            if (combatNumRewardDone != guild.boss.combatNumPass) {
                // 当前只处理非无尽模式的缓存
                guild.game.res.guild.bossRankCache.saveRankPO(guild.uid, guild.boss.combatNumPass, temp);
            }
            combatNumRewardDone = guild.boss.combatNumPass;

            for (int i = 0; i < temp.size(); i++) {
                GuildBossRankItemPO item = temp.get(i);
                // 第几名
                int no = i + 1;
                Role m = guild.game.role.getRole(item.owner.uid);
                if (m != null) {
                    // 换了公会后不能重复领取排行榜奖励
                    if (m.getFarm().guildBoss.checkRankReward(guild.boss.combatNumPass) && !guild.boss.isLastCombat()) {
                        List<Object> mailParams = new ArrayList<>();
                        mailParams.add(guild.boss.combatNumPass);
                        Mail repaetMail =
                                new MailBuilder()
                                        .setContentId(GDMail.Tid.REPEAT_KILL)
                                        .setParamList(mailParams)
                                        .build();
                        guild.game.mail.send(m.getUid(), repaetMail);
                        log.info(
                                "玩家{}尝试重复获取仙盟boss第{}关的奖励", m.getBase().name, guild.boss.combatNumPass);
                        continue;
                    }
                    GuildBossRankRewardRow tpl = guild.game.table.guildBoss.rankReward.getRowByRank(combatTpl.combatNum, no);
                    if (tpl == null) {
                        continue;
                    }

                    MixRes reward = new MixRes(tpl.rewardStr);
                    List<Object> params = new ArrayList<>();
                    params.add(guild.boss.combatNumPass);
                    params.add(no);

                    Mail mail =
                            new MailBuilder()
                                    .setContentId(GDMail.Tid.GUILD_BOSS_RANK)
                                    .setParamList(params)
                                    .setReward(reward)
//                                    .setOperation(GDOperation.GUILD_BOSS_RANK)
                                    .setOperationSub(combatTpl.combatNum)
                                    .build();
                    m.getMail().add(mail);
                }
            }
        }
    }

    @Override
    public int getFuncId() {
        return GDFunc.GuildFunc.BOSS;
    }

}
